<template>
	<view class="page_wrap">
		<custom-header title="添加员工账号" />
		<scroll-view
			:scroll-y="true" 
			scroll-with-animation
			:style="{height:'calc(100vh - 128rpx - 5rpx - '+statusBarHeight+'px)'}"
			class="scroll_content_wrap">
				<view class="bg"></view>
				<view class="_wrap">
					<view class="title">添加员工账号</view>
					<view class="form_wrap">
						<view class="form_item name">
							<view class="icon">
								姓名
							</view>
							<view class="input">
								<input type="text" v-model="name" @input="handleBtnBisabled" placeholder="请输入姓名" />
							</view>
						</view>
						<view class="form_item phone">
							<view class="icon">
								手机号
							</view>
							<view class="input">
								<input type="number" v-model="phone" @input="handleBtnBisabled" placeholder="请输入手机号码" />
							</view>
						</view>
						<view class="form_item code">
							<view class="icon">
								验证码
							</view>
							<view class="input">
								<input type="number" v-model="code" @input="handleBtnBisabled" placeholder="请输入验证码" />
							</view>
							<view
								class="right"
								hover-class="custom_hover"
								:hover-stay-time="200"
								@click="getVerificationCode">
									{{ buttonText }}
							</view>
						</view>
					</view>
				</view>
				
		</scroll-view>
		<view class="footer_btn_wrap">
			<view class="btn_wrap">
				<button
					size="default" 
					type="default" 
					class="btn confirm" 
					hover-class="confirm_hover" 
					:hover-stay-time="200" 
					:class="{'btn_disable':btnBisabled}"
					:loading="btnLoading"
					@click="handleSave">保存账号</button>
			</view>
		</view>
	</view>
	<!-- 自定义消息弹出层 -->
	<custom-popup
		:show="isShowToast" 
		:config="popupConfig"
		@confirm="isShowToast = false" />
</template>

<script setup>
	import { computed, ref, onMounted,onUnmounted } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useStore } from 'vuex'
	import { isvalidPhoneNumber } from '../../utils/validate.js'
	import supplierApi from '@/api/supplier'

	const store = useStore()
	
	const statusBarHeight = computed(()=>{
		return store.getters.statusBarHeight
	})
	
	// 弹窗提示
	const isShowToast = ref(false)
	const popupConfig  = ref({})
	
	const name = ref('')
	const phone = ref('')
	const code = ref('')
	const isCounting = ref(false)
	const countdown = ref(0)
	const totalTime = ref(60)
	const copySuccess = ref(false)
	
	// 计算按钮文本
	const buttonText = computed(() => {
	  if (isCounting.value) {
		return `(${countdown.value}S)重新获取`
	  }
	  return countdown.value === 0 ? '重新获取' : '获取验证码'
	})
	
	// 获取验证码
	const getVerificationCode = async () => {
		
	  if (isCounting.value) return
	  
	  if (!phone.value) {
			popupConfig.value.message = '请输入手机号码'
			isShowToast.value = true
			return
	  }
	  
	  if (!isvalidPhoneNumber(phone.value)) {
	  		popupConfig.value.message = '手机号码格式不正确'
	  		isShowToast.value = true
	  		return
	  }
	  
	  
	  // 这里可以添加实际的API请求
	  try {
		// 显示加载状态
		uni.showLoading({
			title: '发送中...'
		})

		const result = await supplierApi.getAddCode(phone.value)
		// 显示成功提示
		uni.showToast({
			title: '验证码发送成功',
			icon: 'success'
		})

		// 开始倒计时
		startCountdown()

	  } catch (error) {
		console.error('获取验证码失败:', error)

		// 显示错误提示
		popupConfig.value.message = error.message || '验证码发送失败，请重试'
		isShowToast.value = true

	  } finally {
		// 隐藏加载状态
		uni.hideLoading()
	  }
	}
	
	// 开始倒计时
	const startCountdown = () => {
	  isCounting.value = true
	  countdown.value = totalTime.value
	  
	  // 设置定时器
	  const timer = setInterval(() => {
		countdown.value--
		
		if (countdown.value <= 0) {
		  clearInterval(timer)
		  isCounting.value = false
		}
	  }, 1000)
	  
	  // 存储定时器以便清理
	  timerRef.value = timer
	}
	
	// 存储定时器引用
	const timerRef = ref(null)
	
	// 组件卸载时清除定时器
	onUnmounted(() => {
	  if (timerRef.value) {
		clearInterval(timerRef.value)
	  }
	})
	
	// 判断是否可点击按钮
	const btnBisabled = ref(true)
	const handleBtnBisabled = ()=>{
		// 检查所有必填字段
		const isNameValid = name.value && name.value.trim().length > 0
		const isPhoneValid = phone.value && isvalidPhoneNumber(phone.value)
		const isCodeValid = code.value && code.value.trim().length > 0

		btnBisabled.value = !(isNameValid && isPhoneValid && isCodeValid)
	}
	const btnLoading = ref(false)

	// 表单验证
	const validateForm = () => {
		if (!name.value.trim()) {
			popupConfig.value = { message: '请输入员工姓名' }
			isShowToast.value = true
			return false
		}

		if (!phone.value.trim()) {
			popupConfig.value = { message: '请输入手机号码' }
			isShowToast.value = true
			return false
		}

		if (!isvalidPhoneNumber(phone.value)) {
			popupConfig.value = { message: '手机号码格式不正确' }
			isShowToast.value = true
			return false
		}

		if (!code.value.trim()) {
			popupConfig.value = { message: '请输入验证码' }
			isShowToast.value = true
			return false
		}

		return true
	}

	const handleSave = async () => {
		if (btnBisabled.value) return
		if (!validateForm()) return
		if (btnLoading.value) return

		try {
			btnLoading.value = true

			const userData = {
				name: name.value.trim(),
				phone: phone.value.trim(),
				smsCode: code.value.trim(),
			}

			await supplierApi.addShopUser(userData)
			popupConfig.value = {
				message: `员工"${userData.name}"添加成功`
			}
			isShowToast.value = true
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)

		} catch (error) {
			console.error('添加员工失败:', error)
			popupConfig.value = { message:  error.message }
			isShowToast.value = true

		} finally {
			btnLoading.value = false
		}
	}
	
</script>

<style lang="scss">
	.page_wrap{
		min-height: 100vh;
		background: #fff;
	}
	.bg{
		height: 360rpx;
		background: url('https://goods-1312936761.cos.ap-chongqing.myqcloud.com/applet/supplier/my/addzh_bg.png');
		background-size: contain;
	}
	._wrap{
		padding: 0 40rpx;
	}
	.title{
		color: #333333;
		font-size: 32rpx;
		font-weight: bold;
		padding: 30rpx 0 10rpx;
	}
	.form_item{
		height: 80rpx;
		border-radius: 99rpx;
		background: #F8F8F8;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		padding:0 40rpx;
		margin-top: 25rpx;
		color: #666666;
		.icon{
			width: 100rpx;
		}
		.input{
			flex: 1;
			padding-left: 20rpx;
			input{
				width: 100%;
			}
		}
		.right{
			width: 200rpx;
			color: #F5564D;
			text-align: right;
		}
	}
	.input-placeholder{
		font-size: 28rpx;
		color: #C0C4CC;
	}
	input {
		font-size:26rpx;
		color: #666;
	}
</style>
